﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Http
{
    public class HttpService:IHttpService
    {
        public IHttpClientFactory _httpClientFactory { get; set; }

        public async Task<string> PostBody(string Url, Object obj, string authorization = null)
        {
            return await PostJson(Url,JsonConvert.SerializeObject(obj), authorization);
        }

        public async Task<string> PostJson(string url, string json, string authorization = null)
        {
            var httpClient = _httpClientFactory.CreateClient();

            if (!string.IsNullOrWhiteSpace(authorization))
            {
                var aheader = new AuthenticationHeaderValue("Bearer", authorization);
                httpClient.DefaultRequestHeaders.Authorization = aheader;
            }
            httpClient.DefaultRequestHeaders.Add("User-Agent", @"Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)");
            httpClient.DefaultRequestHeaders.Add("Accept", @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpClient.Timeout = TimeSpan.FromSeconds(3);
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.Method = HttpMethod.Post;
            httpRequestMessage.RequestUri = new Uri(url);
            httpRequestMessage.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

            var response = await httpClient.SendAsync(httpRequestMessage);
            return await response.Content.ReadAsStringAsync();
        }

        public async Task<string> PostFrom(string Url, IDictionary<string, object> parameters, string authorization = null)
        {
            StringBuilder buffer = new StringBuilder();
            foreach (string key in parameters.Keys)
            {
                if (buffer.Length > 0) buffer.Append("&");
                buffer.AppendFormat("{0}={1}", key, parameters[key]);
            }
            var httpClient = _httpClientFactory.CreateClient();

            if (!string.IsNullOrWhiteSpace(authorization))
            {
                var aheader = new AuthenticationHeaderValue("Bearer", authorization);
                httpClient.DefaultRequestHeaders.Authorization = aheader;
            }
            httpClient.DefaultRequestHeaders.Add("User-Agent", @"Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)");
            httpClient.DefaultRequestHeaders.Add("Accept", @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpClient.Timeout = TimeSpan.FromSeconds(5);
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.Method = HttpMethod.Post;
            httpRequestMessage.RequestUri = new Uri(Url);
            httpRequestMessage.Content = new StringContent(buffer.ToString(), System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");

            var response = await httpClient.SendAsync(httpRequestMessage);
            return await response.Content.ReadAsStringAsync();

        }

        public async Task<string> GetText(string url, string authorization = null)
        {
            var bytes = await Get(url, authorization);
            return System.Text.UnicodeEncoding.UTF8.GetString(bytes);
        }

        public async Task<byte[]> Get(string url, string authorization = null)
        {
            var httpClient = _httpClientFactory.CreateClient();

            if (!string.IsNullOrWhiteSpace(authorization))
            {
                var aheader = new AuthenticationHeaderValue("Bearer", authorization);
                httpClient.DefaultRequestHeaders.Authorization = aheader;
            }
            httpClient.DefaultRequestHeaders.Add("User-Agent", @"Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)");
            httpClient.DefaultRequestHeaders.Add("Accept", @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpClient.Timeout = TimeSpan.FromSeconds(3);

            var r= await httpClient.GetAsync(url);
            return await r.Content.ReadAsByteArrayAsync();
        }


    }
}
